package com.itlaobing.demo.servlet;

import com.itlaobing.demo.model.UserinfoModel;
import com.itlaobing.demo.util.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

/**
 * @Classname UserEditServlet
 * @Description TODO()
 * @Date 2020/11/12 0012 14:14
 * @Author by Administrator
 * @Version v1.0
 */
@WebServlet("/useredit")
public class UserEditServlet extends HttpServlet {

    private DBHelper db = new DBHelper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");

        if (id == null || id == ""){
            resp.sendRedirect("userlist");
        }
        Integer i = Integer.parseInt(id);
        // 查询用户信息
        String sql = "select  `id`, `username`, `name`, `imgUrl` , `age`, `createDate`, `gender`, `hobby`, `province`, `birthday` from userinfo where id = ?";
        UserinfoModel user = db.executeQuery(sql, UserinfoModel.class, i);

        // 请求转发到 useredit.jsp 页面
        req.setAttribute("model", user);
        req.getRequestDispatcher("WEB-INF/pages/sys/useredit.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 用户 保存 修改信息

        // 获取用户信息
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String birthday = req.getParameter("birthday");
        String age = req.getParameter("age");
        String province = req.getParameter("province");
        String gender = req.getParameter("gender");
        String[] hobby = req.getParameterValues("hobby");
        String temp = Arrays.toString(hobby);
        String h = temp.substring(1, temp.length() - 1);
        System.out.println(h);

        // 做更新操作
        String sql = "update userinfo set name = ?,birthday = ?, age = ?, province = ?, gender = ?, hobby = ? where id =?";
        int rows = db.executeUpdate(sql, name, birthday, age, province, gender, h, id);
        if (rows > 0 ){
            resp.sendRedirect("userlist");
        }else{
            resp.sendRedirect("useredit?id=" + id);
        }
    }
}
